<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="80%"
    top="5%"
    v-if="editOpen"
  >
    <div style="height: 65vh">
      <t-form ref="form" :colon="true" labelAlign="top" :data="formData" labelWidth="100px" :rules="rules">
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="体系名称" label-align="left" name="name">
              <t-input clearable style="width: 390px" v-model="formData.name" :maxLength="100"
                       placeholder="请输入体系名称"></t-input>
              <t-popup v-if="options.length>0">
                <t-button variant="text" class="t-button-link">
                  <t-icon name="add" slot="icon"/>
                  导入历史
                </t-button>
                <template #content>
                  <t-select
                    filterable
                    clearable
                    placeholder="体系名称"
                    :options="options"
                    @change="onChange"
                  />
                </template>
              </t-popup>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总分值" label-align="left" name="score">
              {{formData.score}}
<!--              <t-input-number clearable v-model="formData.score" :min="0" placeholder="请输入"></t-input-number>-->
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="12">
        <t-form-item label="说明" name="note">

          <t-textarea :autosize="{minRows: 5}"
                      v-model="formData.note"  placeholder="请输入内容"/>

        </t-form-item>
          </t-col>
        </t-row>
        <t-divider style="font-size: 20px">基础分</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="基础分" name="reviewItems">-->
          <t-table
            rowKey="id"
            :data="data"
            :columns="columns"
            bordered
            hover
            :selected-row-keys="selectedRowKeys"
            @select-change="(val)=>{selectedRowKeys=val}"
          >
            <template #id="{rowIndex}">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{row}">
              <t-input clearable v-model="row.name"></t-input>
            </template>
            <template #note="{row}">
              <t-textarea :autosize="{minRows: 5}"
                          v-model="row.note" placeholder="请输入内容"/>
            </template>
            <template #floorScore="{row}">
              <t-input-number clearable :min="0" v-model="row.floorScore"></t-input-number>
            </template>
            <template #score="{row}">
              <t-input-number clearable :min="0" v-model="row.score"></t-input-number>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button @click="addData(1)">新增</t-button>
            <t-button @click="upData(1)">上移</t-button>
            <t-button @click="downData(1)">下移</t-button>
            <t-button @click="delData(1)">删除</t-button>
          </div>
        <!--       </t-form-item>-->
        <t-divider style="font-size: 20px">加分项</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore2 }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore2 }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="加分项" name="reviewItems">-->
        <div>
          <t-table
            rowKey="id"
            :data="data2"
            :columns="columns"
            bordered
            hover
            :selected-row-keys="selectedRowKeys2"
            @select-change="(val)=>{selectedRowKeys2=val}"
          >
            <template #id="{rowIndex}">
              {{ rowIndex + 1 }}
            </template>
            <template #name="{row}">
              <t-input clearable v-model="row.name"></t-input>
            </template>
            <template #note="{row}">
              <t-textarea :autosize="{minRows: 5}"
                          v-model="row.note" placeholder="请输入内容"/>
            </template>
            <template #floorScore="{row}">
              <t-input-number clearable :min="0" v-model="row.floorScore"></t-input-number>
            </template>
            <template #score="{row}">
              <t-input-number clearable :min="0" v-model="row.score"></t-input-number>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button @click="addData(2)">新增</t-button>
            <t-button @click="upData(2)">上移</t-button>
            <t-button @click="downData(2)">下移</t-button>
            <t-button @click="delData(2)">删除</t-button>
          </div>
        </div>
        <!--       </t-form-item>-->
      </t-form>

    </div>
  </t-dialog>
  <div v-else>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    :confirmBtn="null"
    width="60%"
    top="5%"
    v-if="isDialog"
  >
    <div style="height: 65vh">
      <t-form ref="form" :colon="true" labelAlign="top" :data="formData" labelWidth="100px">
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="体系名称" label-align="left" name="name">
              {{ formData.name }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总分值" label-align="left" name="score">
              {{ formData.score }}
            </t-form-item>
          </t-col>
        </t-row>
        <t-divider style="font-size: 20px">基础分</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="基础分" name="reviewItems">-->
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          bordered
          hover
          :selected-row-keys="selectedRowKeys"
          @select-change="(val)=>{selectedRowKeys=val}"
        >
          <template #id="{rowIndex}">
            {{ rowIndex + 1 }}
          </template>
        </t-table>
        <!--       </t-form-item>-->
        <t-divider style="font-size: 20px">加分项</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore2 }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore2 }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="加分项" name="reviewItems">-->
        <t-table
          rowKey="id"
          :data="data2"
          :columns="columns"
          bordered
          hover
          :selected-row-keys="selectedRowKeys2"
          @select-change="(val)=>{selectedRowKeys2=val}"
        >
          <template #id="{rowIndex}">
            {{ rowIndex + 1 }}
          </template>
        </t-table>
      </t-form>
    </div>
  </t-dialog>
    <template v-else>
      <t-form ref="form" :colon="true" labelAlign="top" :data="formData" labelWidth="100px">
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="体系名称" label-align="left" name="name">
              {{ formData.name }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总分值" label-align="left" name="score">
              {{ formData.score }}
            </t-form-item>
          </t-col>
        </t-row>
        <t-divider style="font-size: 20px">基础分</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="基础分" name="reviewItems">-->
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          bordered
          hover
          :selected-row-keys="selectedRowKeys"
          @select-change="(val)=>{selectedRowKeys=val}"
        >
          <template #id="{rowIndex}">
            {{ rowIndex + 1 }}
          </template>
        </t-table>
        <!--       </t-form-item>-->
        <t-divider style="font-size: 20px">加分项</t-divider>
        <t-row style="margin-bottom: 12px;font-size: 16px">
          <t-col :span="6">
            <t-form-item label="总下限" label-align="left">
              {{ sumFloorScore2 }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总上限" label-align="left">
              {{ sumScore2 }}
            </t-form-item>
          </t-col>
        </t-row>
        <!--       <t-form-item label="加分项" name="reviewItems">-->
        <t-table
          rowKey="id"
          :data="data2"
          :columns="columns"
          bordered
          hover
          :selected-row-keys="selectedRowKeys2"
          @select-change="(val)=>{selectedRowKeys2=val}"
        >
          <template #id="{rowIndex}">
            {{ rowIndex + 1 }}
          </template>
        </t-table>
      </t-form>
    </template>
  </div>
</template>

<script>

export default {
  name: "add-edit-review-standard",
  components: {},
  props: {
    header: String,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    isDialog: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      visible: true,
      loading: false,
      options: [],
      selectedRowKeys: [],
      selectedRowKeys2: [],
      data: [],
      data2: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 100
        },
        {
          colKey: "name",
          title: "指标名称",
          align: "center",
        },
        {
          colKey: "note",
          title: "指标说明",
          align: "center",
        },
        {
          colKey: "floorScore",
          title: "下限",
          align: "center",
        },
        {
          colKey: "score",
          title: "上限",
          align: "center",
        },

      ],
      columns2: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 100
        },
        {
          colKey: "name",
          title: "指标名称",
          align: "center",
        },
        {
          colKey: "note",
          title: "指标说明",
          align: "center",
        },
        {
          colKey: "floorScore",
          title: "下限",
          align: "center",
        },
        {
          colKey: "score",
          title: "上限",
          align: "center",
        },
      ],
      formData: {
        score: 0,
        name: "",
        reviewItems: []
      },

      rules: {
        name: [{required: true, message: "体系名称不能为空"}],
        score: [{required: true, validator: (val) => val > 0, message: "总分值需要大于0", type: "error"}],
        reviewItems: [{required: true, validator: (val) => val.length > 0, message: "指标列表不能为空", type: "error"}],
      },
      sumFloorScore: 0,
      sumScore: 0,
      sumFloorScore2: 0,
      sumScore2: 0,
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    data: {
      immediate: true,
      deep: true,
      handler(val) {
        let sumFloorScore = 0;
        let sumScore = 0;
        this.data.forEach(val => {
          sumFloorScore += val.floorScore;
          sumScore += val.score;
        })
        this.sumFloorScore = sumFloorScore;
        this.sumScore = sumScore;
        this.formData.score = this.sumScore+this.sumScore2;
      }
    },
    data2: {
      immediate: true,
      deep: true,
      handler(val) {
        let sumFloorScore = 0;
        let sumScore = 0;
        this.data2.forEach(val => {
          sumFloorScore += val.floorScore;
          sumScore += val.score;
        })
        this.sumFloorScore2 = sumFloorScore;
        this.sumScore2 = sumScore;
        this.formData.score = this.sumScore+this.sumScore2;
      }
    }
  },
  created() {
    this.$api.wcx.review.indexList({
      pageNum: 1,
      pageSize: 10000
    }).then(
      (res) => {
        this.options = res.rows.map(val => ({value: val.id, label: val.name}));
      }).catch((e) => {
      this.$message.error(e.toString());
    });
  },
  methods: {
    onChange(val) {
      // 通过val 查询值
      if (typeof (val) === 'number') {
        this.$api.wcx.review.indexGet(val).then((response) => {
          // his.$set(obj,key,value)
          this.formData = response.data;
          this.data = this.formData.reviewItems.filter(item => item.type === "1");
          this.data2 = this.formData.reviewItems.filter(item => item.type === "2");
        });
      }
    },
    getObj() {
      this.$api.wcx.review.indexGet(this.objId).then((response) => {
        this.formData = response.data;
        this.data = this.formData.reviewItems.filter(item => item.type === "1");
        this.data2 = this.formData.reviewItems.filter(item => item.type === "2");
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          //  验证标准列表
          const isValidate = this.data.every((val, index) => {
            const tag = "基础分";
            if (val.name === "") {
              this.$message.error(`${tag}：第${index + 1}条"指标名称"不能为空`);
              return false;
            }
            if (val.floorScore < 0) {
              this.$message.error(`${tag}：第${index + 1}条"下限"需要大于0`);
              return false;
            }
            if (val.score < 0) {
              this.$message.error(`${tag}：第${index + 1}条"上限"需要大于0`);
              return false;
            }
            return true;
          });
          if (!isValidate) {
            return false
          }
          const isValidate2 = this.data2.every((val, index) => {
            const tag = "加分项";
            if (val.name === "") {
              this.$message.error(`${tag}：第${index + 1}条"指标名称"不能为空`);
              return false;
            }
            if (val.floorScore < 0) {
              this.$message.error(`${tag}：第${index + 1}条"下限"需要大于0`);
              return false;
            }
            if (val.score < 0) {
              this.$message.error(`${tag}：第${index + 1}条"上限"需要大于0`);
              return false;
            }
            return true;
          });
          if (!isValidate2) {
            return false
          }
          let totalScore = 0;
          // 合并数组
          this.formData.reviewItems = this.data.concat(this.data2);
          this.formData.reviewItems.forEach((val, index) => {
            this.formData.reviewItems[index].sort = index + 1;
            totalScore += val.score;
          });
          if (totalScore !== this.formData.score) {
            this.$message.error(`指标列表分值总额"${totalScore}"不等于体系总分值"${this.formData.score}"`);
            return false;
          }
          this.loading = true;
          if (this.objId !== 0) {
            this.$api.wcx.review.indexUpdate(this.formData).then((response) => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.wcx.review.indexAdd(this.formData).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    addData(type) {
      if (type === 1) {
        this.data.push({id: Date.parse(new Date()), name: "", floorScore: null, score: null, note: "", type: "1"});
      } else {
        this.data2.push({id: Date.parse(new Date()), name: "", floorScore: 0, score: null, note: "", type: "2"});
      }
    },
    upData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data[0].id === this.selectedRowKeys[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index - 1)
        }
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data2[0].id === this.selectedRowKeys2[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
          this.moveInArray(this.data2, index, index - 1)
        }
      }
    },
    downData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
          this.$message.warning("已是最后一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index + 1)
        }
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data2[this.data2.length - 1].id === this.selectedRowKeys2[0]) {
          this.$message.warning("已是最后一行");
        } else {
          const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
          this.moveInArray(this.data2, index, index + 1)
        }
      }

    },
    delData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.data.splice(index, 1)
        this.selectedRowKeys = [];
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
        this.data2.splice(index, 1)
        this.selectedRowKeys2 = [];
      }

    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style scoped>

</style>
